import java.util.Stack;

/**
 * Created by L.jp
 * Description:请写一个整数计算器，支持加减乘三种运算和括号。
 * User: 86189
 * Date: 2022-07-15
 * Time: 9:52
 */
public class Solution {
    public int solve (String s) {
        // write code here
        if ( s == null ) return 0;
        Stack<Integer> numStack = new Stack<>();
        Stack<Character> opStack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            //处理数字栈
            if ( s.charAt( i ) >= '0' && s.charAt( i ) <= '9' ) {
                if ( i == 0 ) {
                    numStack.add( s.charAt( i ) - '0' );
                } else {
                    if ( s.charAt( i - 1 ) >= '0' && s.charAt( i ) <= '9' ) {
                        int tmp = numStack.pop();
                        int num = tmp * 10 + (s.charAt( i ) - '0');
                        numStack.add( num );
                    } else {
                        numStack.add( s.charAt( i ) - '0' );
                    }
                }
            } else {
                //处理符号栈
                if ( opStack.isEmpty() ) {
                    opStack.add( s.charAt( i ) );
                } else {
                    if ( s.charAt( i ) == '(' ) {
                        opStack.push( s.charAt( i ) );
                    } else if ( s.charAt( i ) == ')' ) {
                        while ( opStack.peek() != '(' ) {
                            cal( numStack , opStack.pop() );
                        }
                        opStack.pop();
                    } else if ( s.charAt( i ) == '*' ) {
                        if ( opStack.peek() == '*' ) {
                            cal( numStack , opStack.pop() );
                        }
                        opStack.push( s.charAt( i ) );
                    } else if ( s.charAt( i ) == '+' || s.charAt( i ) == '-' ) {
                        if ( opStack.peek() != '(' ) {
                            cal( numStack , opStack.pop() );
                        }
                        opStack.push( s.charAt( i ) );
                    }
                }
            }
        }
        while ( !opStack.isEmpty() ) {
            cal( numStack , opStack.pop() );
        }
        return numStack.pop();
    }
    public void cal(Stack<Integer> stackInt, char ope){
        int x = stackInt.pop();
        int y = stackInt.pop();
        if(ope == '*'){
            stackInt.push(x * y);
        }else if(ope == '+'){
            stackInt.push(x + y);
        }else if(ope == '-'){
            stackInt.push(y - x);
        }
    }
}

